package com.computer.fundamentals.concurrentprogram;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Executors线程池使用步骤：
 * 1. 建立线程池
 * 2. 提交线程(Runnable接口或Callable接口)
 * 3. 如果是Callable接口，还需要使用Future接收参数并获取结果
 */
public class ExecutorDemo {

    public static void main(String[] args) {
        System.out.println("提交Callable实例");
        ExecutorService threadPool1 = Executors.newCachedThreadPool();
        Future<String> submit1 = threadPool1.submit(new MyCallable());
        try {
            String res = submit1.get();
            System.out.println("输出结果： " + res);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }finally {
            threadPool1.shutdown();
        }
        System.out.println("\n");

        System.out.println("提交Runnable实例");
        ExecutorService threadPool2 = Executors.newCachedThreadPool();
        threadPool2.submit(new MyRunnable());

    }

}